﻿using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web.Mvc;
using Mondial2014.Models.Competition;
using Mondial2014.Models.Context;
using Mondial2014.Utils;
using Mondial2014.Utils.Events;

namespace Mondial2014.Controllers
{
    public class FixturesController : Controller
    {
        private readonly Mondial2014DbContext m_Context = new Mondial2014DbContext();

        public class FixturesViewMoldel
        {
            public bool Admin { get; set; }
            public IEnumerable<GroupFixture> Fixtures { get; set; }
        }

        public ActionResult Index(int? id)
        {
            var model = new FixturesViewMoldel
            {
                Admin = (id.HasValue && id.Value == 1234),
                Fixtures = m_Context.GetGroupFixtures()
            };
            return View(model);
        }

        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            var fixture = m_Context.GetFixtures().SingleOrDefault(f => f.Id == id);
            if (fixture == null)
            {
                return HttpNotFound();
            }
            return View(fixture);
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Team1Score,Team2Score")] Fixture fixture)
        {
            var f = m_Context.Fixtures.Find(fixture.Id);
            f.Team1Score = fixture.Team1Score;
            f.Team2Score = fixture.Team2Score;
            f.Played = true;
            m_Context.SaveChanges();

            EventDispatcher.PostEvent(new MatchUpdatedEvent(f.Id));

            return RedirectToAction("Index");
        }
    }
}